import * as Api from '../../utils/api.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColors: '',
    basicMall: null,
    hasGoneAway: true,
    productList: [],
    type: '',
    carId: '',//车型ID
    catId: '',//分类ID
    secCatId: '',//二级分类ID
    levelNum: '1',
    screenModel: false,
    categoryList: [],
    selectList: [{
      catName: '全部'
    }]

  },
  consten: function (j1, j2) {
    for (var i = 0; i < j2.length; i++) {
      j1.push(j2[i]);
    }
    return j1
  },
  removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  },
  selectItem(e) {



    let list = this.data.categoryList
    let selectList = this.data.selectList
    let opt = this.data.secCatId.split(',')

    if (e.currentTarget.dataset.main.catKey) {

      this.removeByValue(selectList, e.currentTarget.dataset.main)

      this.removeByValue(opt, e.currentTarget.dataset.main.catId)
      let send = []
      selectList.forEach((item, index) => {
        if (item.catId !== e.currentTarget.dataset.main.catId) {
          send.push(item)
        }
      });
      selectList = send
      list.forEach((item, index) => {
        if (item.catId === e.currentTarget.dataset.main.catId) {
          item.catKey = false
        }
      });



    } else {
      opt = []
      list.forEach((item, index) => {
        if (item.catId === e.currentTarget.dataset.main.catId) {
          selectList.push(e.currentTarget.dataset.main)
          item.catKey = true
        }
        if (item.catKey) {
          opt.push(item.catId)
        }
      });
    }
    this.setData({
      categoryList: list,
      selectList: selectList,
      secCatId: opt.join(',')
    })


    this.getProductList()
    // this.changeModel()


  },
  changeModel(e) {
    console.log(this.data.secCatId)


    this.setData({
      screenModel: !this.data.screenModel
    })
  },
  retBox() {
    return
  },
  goDatil(e) {
    let self = this
    console.log('this.data.oem', this.data.oem)

    if (this.data.oem != '') {
      wx.getStorage({
        key: 'modelOem',
        success: function (res) {
          let modelOem = JSON.parse(res.data)
          let a = {
            createTime: new Date(),
            goodsId: self.data.productList[e.currentTarget.dataset.index].goodsId,
            oem: self.data.oem,
            goodsName: self.data.productList[e.currentTarget.dataset.index].goodsName,
            goodsModelNumber: self.data.productList[e.currentTarget.dataset.index].goodsModelNumber,
            logoUrl: self.data.productList[e.currentTarget.dataset.index].logoUrl,
            oemCode: self.data.productList[e.currentTarget.dataset.index].oemCode
          }
          modelOem.forEach((model, modelIndex) => {
            if (model.goodsId == a.goodsId) {
              self.removeByValue(modelOem, model)
            }
          });
          if (modelOem.length > 30) {
            self.removeByValue(modelOem, modelOem[modelOem.length - 1])
          }
          modelOem.unshift(a)

          let StoryItem = JSON.stringify(modelOem)
          wx.setStorageSync('modelOem', StoryItem);//userId       

        }, fail() {
          let a = [{
            createTime: new Date(),
            goodsId: self.data.productList[e.currentTarget.dataset.index].goodsId,
            oem: self.data.oem,
            goodsName: self.data.productList[e.currentTarget.dataset.index].goodsName,
            goodsModelNumber: self.data.productList[e.currentTarget.dataset.index].goodsModelNumber,
            logoUrl: self.data.productList[e.currentTarget.dataset.index].logoUrl,
            oemCode: self.data.productList[e.currentTarget.dataset.index].oemCode
          }]
          wx.setStorageSync('modelOem', JSON.stringify(a));//userId    

        }
      })
    }

    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })
      wx.navigateTo({
        url: '../product_datil/product_datil?id=' + e.currentTarget.dataset.id + '&carId=' + this.data.carId,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
  },
  getOemList() {
    let self = this
    let url = app.globalData.baseUrl1 + '/goods/parts/search';
    let data = {
      merchantId: app.globalData.merchant.merchantId,
      code: this.data.oem,
      type: this.data.type
    }
    let callBack = (res) => {
      wx.hideToast()

      if (res == null) {
        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {
        console.log("请求数据错误11");
        return;
      }
      this.setData({
        productList: res.data.data
      })
    }
    Api.reqFormPost(url, data, callBack)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 
    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow, options);
      return
    }

      let self = this
      
      if (options.OemNumber) {
        this.setData({
          type: options.type,
          oem: options.OemNumber
        })
        
        this.getOemList()
      } else {

        wx.setNavigationBarTitle({
          title: decodeURI(options.catname)
        })
    
        let opt = {
          themeColors: app.globalData.merchant.themeColors,
          basicMall: app.globalData.merchant.basicMall,
          carId: options.id, catId: options.catid, secCatId: '', levelNum: options.levelNum
        }
        if (options.levelNum === 2) {
          opt.catId = options.catid
        }
        this.setData(opt)
        this.getSecCatList(options.secCatId);
      }


  },
  //  二级分类列表
  getSecCatList(secCatId) {

    let self = this
    let url = app.globalData.baseUrl + '/merchant/catlist'
    let data = {}
    if (this.data.catId != '') {
      data = {
        merchantId: app.globalData.merchant.merchantId,
        modelId: this.data.carId,
        parentId: this.data.catId
      }
    } else {
      data = {
        merchantId: app.globalData.merchant.merchantId,
        modelId: this.data.carId
      }
    }
    console.log(data, 'data')
    //发起网络请求
    let callBack = (res) => {

      if (res == null) {
        console.log("网络请求错误！");
        return;
      }

      if (res.statusCode != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.statusCode === 200) {
        console.log(1, res.data.data.children)

    
        self.setData({
          categoryList: res.data.data.children
        })
        let list = this.data.categoryList
        let selectList = this.data.selectList
        let secCatIdList = []
        if (this.data.secCatId != '') {
          secCatIdList = this.data.secCatId.split(',')
        }



        list.forEach((item, index) => {
          if (item.catId === secCatId) {
            selectList.push(list[index])
            item.catKey = true
          }
          if (item.catKey) {
            secCatIdList.push(item.catId)
          }
        });

        this.setData({
          categoryList: list,
          selectList: selectList,
          secCatId: secCatIdList.join(',')
        })
        console.log('select', this.data.selectList)

        this.getProductList();
      }


    }
    Api.reqFormPost(url, data, callBack)
  },
  // 商品列表
  getProductList() {
    let self = this
    let url = app.globalData.baseUrl1 + '/goods/front/list'
    let data = {

    }
    if (app.globalData.userId == null) {
      data = {
        merchantId: app.globalData.merchant.merchantId,
        firstCatId: this.data.catId,//一级分类id
        secCatIds: this.data.secCatId,//二级分类id
        carId: this.data.carId
      }
    } else {
      data = {
        merchantId: app.globalData.merchant.merchantId,
        userId: app.globalData.userId,
        firstCatId: this.data.catId,//一级分类id
        secCatIds: this.data.secCatId,//二级分类id
        carId: this.data.carId
      }
    }


    //发起网络请求
    let callBack = (res) => {
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }

      if (res.statusCode != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.statusCode === 200) {
        console.log('商品列表', res)
        let productImage = []
        for (let i = 0; i < res.data.data.length; i++) {
          if (res.data.data[i].imageList.split(',').length > 0) {
            productImage.push(res.data.data[i].imageList.split(',')[0])
          } else {
            productImage.push('')
          }
        }
        console.log(res.data.data.length)
        self.setData({
          productImage: productImage,
          productList: res.data.data
        })

      }


    }
    Api.reqFormPost(url, data, callBack)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.merchant === null) {
      return
    } 
    if (app.globalData.merchant.mustLogin && app.globalData.userId === null) {
      wx.navigateTo({
        url: '/pages/core/login/login',
        success() {
          wx.showToast({
            title: '请先登陆',
            icon: 'loading',
            duration: 1000
          })
        }
      })
      return
    }
           this.setData({ hasGoneAway: false })
 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})